;
cmedit.TaskSystem = (function($, window, document) {
	var thisContext;
	var topUtil; //顶层工具类
    var startPage=1;
    var loadTimeout = cmedit.global.loadTimeout;
	var columnInfo = JSON.parse(window.parent.sessionStorage.getItem(cmedit.global.columnInfo));
    var allColumnInfo = JSON.parse(window.parent.sessionStorage.getItem(cmedit.global.allColumnInfo));
	var userColumnIds = window.parent.sessionStorage.getItem(cmedit.global.userColumnIds);
	var tenantId = window.localStorage.getItem("tenantId");
	var userId = window.sessionStorage.getItem("userId");
	var token = window.sessionStorage.getItem("token");
	var selectIds=[];
	var listTotalCount;
    var listPageSize;
    var orderName='';
    var pageNow;
    var orderDirection='';
	var TaskSystemClass = function() {

	}
	TaskSystemClass.prototype = {
		constructor : TaskSystemClass,

		init : function() {
			thisContext = this;
			topUtil = window.parent.cmedit.global;
			thisContext.initViewStyle();
			thisContext.initColumn();
			thisContext.initData();
			thisContext.initEvent();
		},
		refresh : function(){
        	$('#manutaskTable').bootstrapTable('refresh');
        },
		/**
		 * 初始化页面视图
		 */
		initViewStyle : function(mainGuid) {
			$('.re_contleft .slimScrollDiv').css('height',$(document).height()-116+'px');
            $('.tab-content').css('height',$('.portlet-body').innerHeight()+'px');
//            $('.line-body').css('height',$('.cont_container').innerHeight()-203+'px');
//
//            /*修改滚动条样式*/
//            var linescroll_height=$('.line-body').height();
//            thisContext.scrollType('line-body',linescroll_height);
            
            $('#startTime').datepicker({clearBtn: true,format: 'yyyy-mm-dd',autoclose: true});
            $('#endTime').datepicker({clearBtn: true,format: 'yyyy-mm-dd',autoclose: true});
		},

		/**
         * 初始化事件
         */
        initEvent : function() {
            $('.nav-link').on('click',function () {
                $('.nav-link').removeClass('nav_active');
                $(this).addClass('nav_active');
            });
            $('.container_buttons button').on('click',function () {
                $(this).addClass('active').siblings().removeClass('active');
                thisContext.initData();
            });
            //栏目筛选功能
			/*$('#preReportColumn').change(function(){
				thisContext.initData();
			});*/
			//时间筛选绑定change事件
			/*$('#endTime').change(function() {
				thisContext.initData();
			});*/
			//刷新列表
			$('.task_refresh').on('click',function(){
				$("#preReportColumn").val('');
				$('#searchContent').val('');
				$("#preReportColumn").selectpicker('refresh');
				$(".container_buttons button[states='']").addClass('active').siblings().removeClass('active');
				$('.date-picker input').val('').datepicker('clearDates');	
				//thisContext.initData();
			});
        },
        /**
         * 时间排序
         */
        orderby : function(id,orderDirectionName){
        	orderName=id;
        	orderDirection=orderDirectionName;
        	 thisContext.initData(pageNow);
        },
		/**
		 * 初始化数据
		 */
		initData : function(_currentPage,_pageSize) {
			window.parent.cmedit.ManuscriptSystem.updatePortalStorageExpireTime();
//			$('#allSelected').prop('checked',false);
//			$('#manutaskBody').html(cmedit.global.loaderHtml);
			var $tableid = $('#manutaskTable');
        	var url = cmedit.global.cmsPath+"ManuscriptMainController/getCensorTaskManuscriptByPage";
        	var gc = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditTask));
        	var cmeditList = JSON.parse(window.sessionStorage.getItem(cmedit.global.cmeditTypes));
        	var hasCheckbox = true;
        	if($('#searchContent').val()!=null && $('#searchContent').val()!=''){
        		var title=$('#searchContent').val();
        	}else{
        		var title='';
        	}
//          if($('#endTime').val()!=null && $('#endTime').val()!=''){
            if(($('#endTime').val()!=null && $('#endTime').val()!='') || ($('#startTime').val()!=null && $('#startTime').val()!='')){
        		var dateranges=$("#startTime").val()+" - "+$("#endTime").val();
        	}else{
        		var dateranges='';
        	}
            var currentPage = _currentPage ? _currentPage : 1;
            var pageSize =_pageSize ? _pageSize : 10;
        	var states=$(".container_buttons button[class*='active']").attr("states");
        	var columnId=$("#preReportColumn").val()!=""?$("#preReportColumn").val():"";
        	var queryParams={
        			userColumnIds:userColumnIds,
            		mainHeader:title,
            		mainType:"0",//CMS稿件
            		columnId:columnId,
            		dateranges:dateranges,
            		clbCensorState:states,
                    currentPage:currentPage,
                    pageSize:pageSize
            	};
        	var tableParams = {
        			$tableid: $tableid,
        			url: url,
	        		gc: gc,
	        		hasCheckbox: hasCheckbox,
	        		tenantId: tenantId,
	        		userId: userId,    
	        		token: token,
	        		cmeditList: cmeditList,
	        		resourceType : "manuTask",
	        		callBackLoadData:function(start,size){
	                	thisContext.initData(start,size);
	                }

            };
            console.log('tableParams:'+tableParams);
            TableInit(tableParams, queryParams);       	
        	/*var datalist={
        		userColumnIds:userColumnIds,
        		currentPage:page,
        		pageSize:'10',
        		mainHeader:title,
        		mainType:"0",//CMS稿件
        		columnId:columnId,
        		dateranges:dateranges,
        		clbCensorState:states,
        		sortField:orderName,
        		sortDirection:orderDirection
        	};
        	console.log(datalist);
        	topUtil.ajaxRequest({
				type: "post",
				async: false,
				contentType: "application/json;charset=UTF-8",
				dataType: "json",
				url: cmedit.global.cmsPath+"ManuscriptMainController/getCensorTaskManuscriptByPage",
				data: datalist,
				success: function(data) {
					if(data.status) {
						listTotalCount = data.data.totalCount;
						listPageSize = data.data.pageSize;
						var html=template('manutaskList',data);
						if(html){
							setTimeout(function(){
								$('#manutaskBody').html(html);
							},loadTimeout)
						}else{
							setTimeout(function(){
								$('#manutaskBody').html("<span class='noResults'>暂无数据<span>");
							},loadTimeout)
							
						}
						$("#pagination").html('');
						thisContext.initPage(data.data.totalPage);
						if(!startPage){
							$('#pagination').whjPaging('setPage',1,data.data.totalPage);
						}
					}else{
						$.notify(data.msg);
					}
				}
			});*/
		},
		
		 /**
         * 初始化分页
         */
        initPage : function(totalPage){
        	$("#pagination").whjPaging({
                /*pageSizeOpt: [
                    {'value': 5, 'text': '5/page', 'selected': true},
                    {'value': 10, 'text': '10/page'},
                    {'value': 15, 'text': '15/page'},
                    {'value': 20, 'text': '20/page'}
                ],*/
                totalPage: totalPage,
                showPageNum: 4,
                firstPage: '<i class="iconfont icon-diyiye"></i>',
                previousPage: '<i class="iconfont icon-shangyiye"></i>',
                nextPage: '<i class="iconfont icon-xiayiye"></i>',
                lastPage: '<i class="iconfont icon-weiye"></i>',
                skip: 'skip',
                confirm: 'go',
                refresh: 'refresh',
                totalPageText: 'the total {} pages',
                isShowFL: true,
                isShowPageSizeOpt: false,
                isShowSkip: false,
                isShowRefresh: false,
                isShowTotalPage: false,
                isResetPage: true,
                callBack: function (currPage, pageSize) {
                	pageNow=currPage;
                	thisContext.initData(currPage);
                }
            });
        	/*$('#pagination').whjPaging('setPage',1,totalPage);*/
        },
        
        
        /**
         *滚动条样式
         */
        scrollType : function(scrollId,scrollHeight) {
            $('.'+scrollId).slimScroll({
                height: scrollHeight,//可滚动区域高度
                size: '5px',//组件宽度
                color: '#999',//滚动条颜色
                railOpacity: .3,//滚动条透明度
                disableFadeOut: true,//鼠标经过可滚动区域时显示组件，离开时隐藏组件
                wheelStep: 20, //滚轮滚动量
                alwaysVisible: true,//始终显示组件
                borderRadius: '7px' //滚动条圆角
            });
        },

        /**
         * 全选
         */
        allfileSelected : function(){
            if($('#allSelected').prop('checked')){
                $('.select-check').prop('checked',true);
                $('.list_check').addClass('list_checked');
                $('.res-one').addClass('ulChecked');

            }else{
                $('.select-check').prop('checked',false);
                $('.list_check').removeClass('list_checked');
                $('.res-one').removeClass('ulChecked');
            }
        },
        
        /**
         * 选择框点击事件
         */
        listOneCheckClick : function(obj){
            if(!$(obj).prev().prop('checked')){
                $(obj).addClass('list_checked');
                if($('.list_checked').length >= 10){
                    $('#allSelected').prop('checked',true);
                }
            }else{
                $(obj).removeClass('list_checked');
                $('#allSelected').prop('checked',false);
                $('#allSelected').next().removeClass('list_checked');
            }
        },
        
        /**
         *  初始化栏目
         */
        initColumn : function(){
       	 	var bigColumnId = window.parent.sessionStorage.getItem(cmedit.global.bigColumnId);
       	 	//判断该用户是否属于大采访部
       	 	if(userColumnIds.indexOf(bigColumnId) > -1){
       	 		for(var i = 0;i < allColumnInfo.length; i++){
            		$("#preReportColumn").append('<option value="'+allColumnInfo[i].id+'">'+allColumnInfo[i].name+'</option>');
            	}
       	 	}else{
       	 		for(var i = 0;i < columnInfo.length; i++){
            		$("#preReportColumn").append('<option value="'+columnInfo[i].id+'">'+columnInfo[i].name+'</option>');
            	}
       	 	}
       	 	$("#preReportColumn").selectpicker('refresh');
        },
        /**
         * 详情页
         */
        entertaskDetail : function(mainGuid,mainHeader){
        	if(mainHeader == "manuscript"){
        		mainHeader = $("#"+mainGuid).attr("mainheader");
        	}
        	window.parent.cmedit.ManuscriptSystem.enterDetail(mainGuid,mainHeader,"Task");
        },
        /**
         * 初始化审核人员列表
         */
        initCensorPerson : function(mainColumnId,mainGuid){
        	var postData = {
        		columnId : mainColumnId,
        		mainGuid : mainGuid
        	}
        	topUtil.ajaxRequest({
				type: "post",
				async: false,
				dataType: "json",
				url: cmedit.global.cmsPath+"UserInfoController/getCensorPersonList",
				data : postData,
				success: function(data) {
					if(data.status) {
						var list = data.data;
						var appendHtml = '<option value="">请选择</option>';
						for(var i=0;i<list.length;i++){
			 				appendHtml += '<option value="'+list[i].id+'">'+list[i].name+'</option>';
			 			}
						var censorPerson ='<select id="censorPerson" class="selectpicker bs-select form-control" data-live-search="true" data-size="8">'+appendHtml+'</select>';
						var nextCensor = '<select id="nextCensor" class="selectpicker bs-select form-control" data-live-search="true" data-size="8">'+appendHtml+'</select>';
						$('#checkSelect',parent.document).html('');
						$('#checkSelect',parent.document).html(censorPerson);
						$('#nextCensorSelect',parent.document).html('');
						$('#nextCensorSelect',parent.document).html(nextCensor);
						/*$("#censorPerson",parent.document).append(appendHtml);*/
						//$("#nextCensor",parent.document).html(appendHtml);
			     		$("#censorPerson",parent.document).selectpicker('refresh');
			     		$("#nextCensor",parent.document).selectpicker('refresh');
					}else{
						$.notify(data.msg);
					}
				}
			});
        },
        
        /**
         * 反审核
         */
        backCensorTask : function(mainGuid){
        	var checkData={
        		"mainGuid":	mainGuid
        	}
        	topUtil.ajaxRequest({
        		type: "post",
        		async: true,
        		dataType: "json",
        		url: cmedit.global.cmsPath+"CensorController/backCensorTask",
        		data: checkData,
        		success: function(data){
        			if(data.status) {
        				thisContext.initData();
        			}else{
        				$.notify(data.msg);
        			}
        		}
        	});
        },
        
        /**
         * 审核弹框
         */
        taskModal : function(mainGuid,mainColumnId,censorType){
        	var checkData={
        		"mainGuid":	mainGuid
        	}
        	topUtil.ajaxRequest({
				type: "post",
				async: true,
				dataType: "json",
				url: cmedit.global.cmsPath+"ManuscriptMainController/censorStrategyExist",
				data: checkData,
				success: function(data){
					if(data.status) {
						//清空审核弹框里的数据
						$('#newTargetList', parent.document).html('');
						$('#auditComments',parent.document).val("");
						$('#fromTask',parent.document).val("manuTask");
						$('#isStepback',parent.document).val(data.data[0].cstIsStepback);
						if(censorType){
							$('#censorPass',parent.document).prop("checked","checked");
						}else{
							$('#censorBack',parent.document).prop("checked","checked");
						}
						$('#censorMainGuid',parent.document).val(mainGuid);
						if (data.data[0].cstIsNominator == 1) {
                        	thisContext.initCensorPerson(mainColumnId, mainGuid);
                        }
						window.parent.cmedit.ManuscriptSystem.taskmodalShow(data.data[0].cstIsNominator,false);
					}else{
						$.notify(data.msg);
					}
				}
			});
        	/**/
        },
        /**
         * 列表数据删除操作
         */
        listoneDel : function(){
//        	window.parent.cmedit.ManuscriptSystem.listoneDel(mainGuid,'manuTask');
        },
        
        /**
         * 全选
         */
        allfileSelected : function(){
            if($('#allSelected').prop('checked')){
                $('.select-check').prop('checked',true);
                $('.list_check').addClass('list_checked');
                $('.res-one').addClass('ulChecked');
                selectIds=[];
                for(var i=0;i<$('#manutaskBody .list_checked').length;i++){
                	selectIds.push($('#manutaskBody .listone_check').eq(i).attr('id'));
                }
            }else{
                $('.select-check').prop('checked',false);
                $('.list_check').removeClass('list_checked');
                $('.res-one').removeClass('ulChecked');
                selectIds=[];
            }
        },
        /**
         * 选择框点击事件
         */
        listOneCheckClick : function(obj,id){
        	/*setTimeout(function(){*/
	            if(!$(obj).prev().prop('checked')){
	                $(obj).addClass('list_checked');
	                selectIds.push(id);
	                if(listTotalCount >= listPageSize){
	                	if($('.list_checked').length >= listPageSize){
	                        $('#allSelected').prop('checked',true);
	                    }
	                }else{
	                	if($('#manutaskBody .list_checked').length == listTotalCount){
	                    	$('#allSelected').prop('checked',true);
	                    }
	                }
	            }else{
	                $(obj).removeClass('list_checked');
	                selectIds.splice($.inArray(id,selectIds),1);
	                $('#allSelected').prop('checked',false);
	                $('#allSelected').next().removeClass('list_checked');
	            }
        	/*},200);*/
        },
        
        /**
         * 批量删除
         */
        selectDelect : function(){
        	var choosenList =$('#manutaskTable').bootstrapTable('getSelections');
        	if (choosenList.length == 0) {
        		$.notify("请先选择记录！");
				$('.manuLoader').hide();
				return false;
        	}
        	var selectIds=[];
        	for(var i=0; i <choosenList.length;i++){
        		var mainObj = {};
            	mainObj.mainGuid = choosenList[i].mainGuid;
            	mainObj.mainCreateUserId = choosenList[i].mainCreateUserId;
            	mainObj.mainStatus = choosenList[i].mainStatus;
                selectIds.push(mainObj);
    		}
    		window.parent.cmedit.ManuscriptSystem.delResoure(selectIds,"manuTask");
        },
        
        /**
         * 下载稿件选择
         * @returns {Boolean}
         */
        selectDownload : function(){
        	var choosenList =$('#manutaskTable').bootstrapTable('getSelections');
        	if(choosenList.length == 0){
        		$.notify("请先选择记录！");
				$('.manuLoader').hide();
				return false;
        	}
//        	else if(choosenList.length > 1){
//        		$.notify("同时只能下载一条稿件！");
//				$('.manuLoader').hide();
//				return false;
//        	}
        	else{
                var mainGuids = [];
                var columnIds = [];
                var mainType = "";
                var params = {};
                for (var i = 0; i < choosenList.length; i++) {
                    mainGuids.push(choosenList[i].mainGuid);
                    columnIds.push(choosenList[i].mainColumnId);
                    mainType = choosenList[i].mainType;
                }
                params["mainGuids"] = mainGuids;
                params["columnIds"] = columnIds;
                params["mainType"] = mainType;
        		window.parent.cmedit.ManuscriptSystem.showDownloadModal(params);
        	}
        },
        
	};

	return new TaskSystemClass();
})(jQuery, window, document);
$(cmedit.TaskSystem.init());